package com.mmall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.google.common.collect.Lists;

import com.mmall.common.Const;
import com.mmall.common.ServerResponse;
import com.mmall.dao.CategoryMapper;
import com.mmall.dao.ProductMapper;
import com.mmall.pojo.Category;
import com.mmall.pojo.Product;
import com.mmall.service.CategoryService;
import com.mmall.service.ProductService;
import com.mmall.util.FtpUtil;
import com.mmall.util.PropertiesUtil;
import com.mmall.vo.ProductDetailVo;
import com.mmall.vo.ProductListVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;


@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
     private ProductMapper productMapper;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private CategoryMapper categoryMapper;

    private Logger logger = LoggerFactory.getLogger(ProductServiceImpl.class);


    //搜索和分类查询
     public ServerResponse selectProductByKeywords(String keyword,Integer categoryId, int pageSize,int pageNum, String orderBy){

         if(StringUtils.isBlank(keyword)&&categoryId==null){
             return ServerResponse.createServerResponseByFailure("参数错误");
         }
         List<Integer> categoryIdList=null;
         if(categoryId!=null){
             categoryIdList=categoryService.getChildrenAllCategory(categoryId).getData();
         }
         if(StringUtils.isNotBlank(keyword)){
            keyword=new StringBuffer().append("%").append(keyword).append("%").toString();
         }
         PageHelper.startPage(pageNum,pageSize);
         //排序处理
         if(StringUtils.isNotBlank(orderBy)){
             if(Const.produceListOrderBy.PRICE_ASC_DESC.contains(orderBy)){
                 String[] orderByArray = orderBy.split("_");
                 PageHelper.orderBy(orderByArray[0]+""+orderByArray[1]);
             }
         }
         List<Product>   productList =  productMapper.selectProductByKeywordsIds(keyword, categoryIdList);
         PageInfo pageInfo = new PageInfo(productList);
         return  ServerResponse.createServerResponseBySuccess(pageInfo);
     }
    public ServerResponse updateStatus(Integer status,Integer categoryId){
         Product product = new Product();
         product.setCategoryId(categoryId);
         product.setStatus(status);
        int result=productMapper.updateSelective(product);
        if(result==1){
            return ServerResponse.createServerResponseBySuccess("状态修改成功!");
        }
        else{
            return ServerResponse.createServerResponseBySuccess("状态修改失败!");
        }

    }

     public String uploadFile(MultipartFile file,String path){
         String   originalFilename = file.getOriginalFilename();
         String   fileExtentionName = originalFilename.substring(originalFilename.lastIndexOf(".")+1);//得到文件的扩展名
         String   newFileName = UUID.randomUUID().toString()+"."+fileExtentionName;
         System.out.printf(originalFilename+"---"+fileExtentionName+"------"+newFileName);
         File filedir = new File(path);
         if (!filedir.exists()){
             filedir.mkdir();
         }
         File targetFile = new File(path,newFileName);
         try {
             file.transferTo(targetFile);//上传到本地服务器上
             //上传到ftp服务器
             FtpUtil.uploadFile(Lists.<File>newArrayList(targetFile));
             //删除本地/upload下的文件
             targetFile.delete();
         } catch (IOException e) {
             e.printStackTrace();
             logger.error("上传文异常");
         }

  return targetFile.getName();

     }
    public ServerResponse saveOrUpdate(Product product){
         int result;
         if(product.getCategoryId()!=null){
             result=productMapper.updateByPrimaryKey(product);
             if(result==1) {
                 return ServerResponse.createServerResponseBySuccess("更新成功");
             }
                 return  ServerResponse.createServerResponseByFailure("更新异常");
         }
         else{
             result=productMapper.insert(product);
             if(result==1) {
                 return ServerResponse.createServerResponseBySuccess("保存成功");
             }

                return ServerResponse.createServerResponseBySuccess("插入异常");
         }

    }

    public  ServerResponse manageDetail(Integer productId){

        if(productId==null){
            return ServerResponse.createServerResponseByFailure("数据参数错误");
        }
        Product product = productMapper.selectByPrimaryKey(productId);
        ProductDetailVo productDetailVo = assembleProductDetailVo(product);
       return ServerResponse.createServerResponseBySuccess(productDetailVo);
    }


   public ServerResponse  searchProduct(Integer productId,String productName,Integer pageNum,Integer pageSize){

        PageHelper.startPage(pageNum,pageSize);
        if(StringUtils.isNotBlank(productName)){
            productName=new StringBuffer().append("%").append(productName).append("%").toString();
        }
        List<Product> productList =  productMapper.searchProduct(productId,productName);
        List<ProductListVo> productListVoList = Lists.newArrayList();
         for(Product product:productList){
             productListVoList.add(assembleProductListVo(product));
         }
        PageInfo page = new PageInfo(productListVoList);
       return ServerResponse.createServerResponseBySuccess(productList);
   }
//
    public ServerResponse selectProductList(Integer pageNum,Integer pageSize){

       PageHelper.startPage(pageNum,pageSize);
       List<Product> productList = productMapper.selectAll();
       List<ProductListVo> productListVoList = Lists.newArrayList();

       for(Product product:productList){
           productListVoList.add(assembleProductListVo(product));
       }
       PageInfo pageInfo = new PageInfo(productListVoList);
       return ServerResponse.createServerResponseBySuccess(pageInfo);
   }

    private ProductDetailVo   assembleProductDetailVo(Product product){

        ProductDetailVo productDatailVo  = new ProductDetailVo();

        productDatailVo.setId(product.getId());
        productDatailVo.setCategoryId(product.getCategoryId());
        productDatailVo.setDetail(product.getDetail());
        productDatailVo.setName(product.getName());
        productDatailVo.setPrice(product.getPrice());
        productDatailVo.setSubtitle(product.getSubtitle());
        productDatailVo.setMainImage(product.getMainImage());
        productDatailVo.setSubImages(product.getSubImages());
        productDatailVo.setStock(product.getStock());


        productDatailVo.setImageHost(PropertiesUtil.getProperty("tp.server.http.prefix","http:img.happymmall.com/"));
        Category category = categoryMapper.selectByPrimaryKey(product.getCategoryId());
        if(category==null){
            category.setParentId(0);//如果查询出的为null,则默认是根目录下的
        }
        productDatailVo.setParentCategoryId(category.getParentId());
        return productDatailVo;

    }


    private ProductListVo  assembleProductListVo(Product product){
        ProductListVo productListVo  = new ProductListVo();
        productListVo.setStatus(product.getStatus());
        productListVo.setId(product.getId());
        productListVo.setCategoryId(product.getCategoryId());
        productListVo.setName(product.getName());
        productListVo.setPrice(product.getPrice());
        productListVo.setSubtitle(product.getSubtitle());
        productListVo.setMainImage(product.getMainImage());
        productListVo.setImageHost(PropertiesUtil.getProperty("tp.server.http.prefix","http:img.happymmall.com/"));
        return productListVo;

    }







}
